package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.IReportService;
import com.sky.service.IWorkSpaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.TopTenVo;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
@Transactional
public class ReportServiceImpl implements IReportService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IWorkSpaceService workSpaceService;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合存放从begin 到 end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        List<Double> turnOverList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            //日期计算，就算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate localDate : dateList) {
            //查询date日期对应的营业数据，营业额实是指：已完成的订单
            //select sum(amount) from orders where order_time > ? and order_time< ? and status=5;
            LocalDateTime localDateTimeBegin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime localDateTimeEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            Map<String, Object> map = new HashMap();
            map.put("begin", localDateTimeBegin);
            map.put("end", localDateTimeEnd);
            map.put("status", 5);
            Double turnOver = orderMapper.sumByMap(map);
            turnOver = turnOver == null ? 0.0 : turnOver;
            turnOverList.add(turnOver);
        }
        String join = StringUtils.join(dateList, ",");
        String join1 = StringUtils.join(turnOverList, ",");
        return TurnoverReportVO.builder()
                .dateList(join)
                .turnoverList(join1)
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        //存放每天新增用户数量 select count(id) from user where creat_time>=localDateTimeBegin and
        // creat_time<= localDateTime;
        List<Integer> newUserList = new ArrayList<>();
        //存放每天的总用户数量 select count(id) from user where creat_time < ?
        List<Integer> totalUserList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate localDate : dateList) {
            LocalDateTime localDateTimeBegin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime localDateTimeEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("end", localDateTimeEnd);
            Integer totalUser = userMapper.countByMap(map);
            map.put("begin", localDateTimeBegin);
            Integer newUser = userMapper.countByMap(map);
            totalUser = totalUser == null ? 0 : totalUser;
            newUser = newUser == null ? 0 : newUser;
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        /**
         * 封装结构数据
         */
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ",")).
                build();
    }

    @Override
    public TopTenVo topTen(LocalDate begin, LocalDate end) {
        LocalDateTime localDateTimeBegin = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime localDateTimeEnd = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getTopTen(localDateTimeBegin, localDateTimeEnd);
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        goodsSalesDTOList.forEach((it) -> {
            nameList.add(it.getName());
            numberList.add(it.getNumber());
        });
        return TopTenVo.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 1 查询数据库，获取营业数据--查询最近30天的数据
        LocalDate begin = LocalDate.now().minusDays(30);//获取当前日期
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        /*--查询概览数据--*/
        BusinessDataVO businessData = workSpaceService.getBusinessData(beginTime, endTime);
        // 2 通过poi将数据写入excel文件中
        InputStream inputStream = this.getClass().getClassLoader()//获取类加载器
                .getResourceAsStream("template/运营数据报表模板.xlsx");
        //基于模板文件来创建一个新的excel文件
        try {
            if (inputStream != null) {
                XSSFWorkbook excel = new XSSFWorkbook(inputStream);
                //填充数据 时间片
                XSSFSheet sheet = excel.getSheet("Sheet1");
                sheet.getRow(1).getCell(1).setCellValue("时间:" + begin + "至" + end);
                XSSFRow row3 = sheet.getRow(3);
                row3.getCell(2).setCellValue(businessData.getTurnover());//添加了营业额
                row3.getCell(4).setCellValue(businessData.getOrderCompletionRate());//添加订单完成率
                row3.getCell(6).setCellValue(businessData.getNewUsers());//新增用户数
                //获得第五行
                XSSFRow row4 = sheet.getRow(4);
                row4.getCell(2).setCellValue(businessData.getValidOrderCount());//有效订单
                row4.getCell(4).setCellValue(businessData.getUnitPrice());//平均客单价
                // 填充明细数据
                for (int i = 0; i < 30; i++) {
                    LocalDate date = begin.plusDays(i);
                    BusinessDataVO businessDataWithOneDay = workSpaceService
                            .getBusinessData(LocalDateTime.of(date, LocalTime.MIN)
                                    , LocalDateTime.of(date, LocalTime.MAX));//获取到精确的某一天数据
                    XSSFRow row = sheet.getRow(7 + i);//拿到第8+i行
                    row.getCell(1).setCellValue(String.valueOf(date));//添加日期
                    row.getCell(2).setCellValue(businessDataWithOneDay.getTurnover());
                    row.getCell(3).setCellValue(businessDataWithOneDay.getValidOrderCount());
                    row.getCell(4).setCellValue(businessDataWithOneDay.getOrderCompletionRate());
                    row.getCell(5).setCellValue(businessDataWithOneDay.getUnitPrice());
                    row.getCell(6).setCellValue(businessDataWithOneDay.getNewUsers());
                }
                // 3 通过输出流，将文件下载到客户端浏览器
                ServletOutputStream outputStream = response.getOutputStream();
                excel.write(outputStream);
                outputStream.close();
                excel.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
